import path from 'path';
const conf = think.config('upload');
const FtpSocket = think.adapter('socket', 'ftp');

function log(...args){
	conf.log !== false && console.log(...args);
}

//上传ftp
export async function send(files, opt = {}) {

	if(!files){
		throw new Error("请求数据有误");
	}

	let ftp = FtpSocket.getInstance(conf.ftp, 'ftp');

	// log( 'ftp connect: ' + JSON.stringify(connectConf) );

	log('fileUplod time start:', (new Date()).getTime());

	let nowDate = new Date();
	let ftpFolder = path.join(conf.ftpPath, `${nowDate.getFullYear()}${nowDate.getMonth()+1}${nowDate.getDate()}`).replace(/\\/g, '/');

	try {
		// 检查目录是否存在不存在会报错
		let list = await ftp.wrap('listSafe', ftpFolder, false);
	} catch (e) {
		log('mkdir', ftpFolder);
		try {
			await ftp.wrap('mkdir', ftpFolder);
		} catch(e) {
			log('mkdir err', e)
			await new Promise((resolve) => {
				setTimeout(resolve, 10)
			});
		}
	}

	const ftpUrl = !opt.justPath ? conf.ftpUrl : '';

	return think.error(Promise.all(Object.values(files).map((file) => {
		let ftpFileName = path.basename(file.path);

		log('put', file.path, `${ftpFolder}/${ftpFileName}`);

		return ftp.put(file.path, `${ftpFolder}/${ftpFileName}`)
			.then(() => `${ftpUrl}/${ftpFolder}/${ftpFileName}`);
	})).then((uploadPaths) => {
		log('time end:',(new Date()).getTime());
		// ftp.close();
		return {
			"cmd": "upload",
			"result": 0,
			"resultNote": "Success",
			"detail": {
				"path" : uploadPaths
			}
		};
	}));
};